<template>
  <div class="article-list-container">
    <a-card title="文章管理" :bordered="false">
      <!-- 搜索和操作栏 -->
      <div class="table-operations">
        <a-space>
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索文章标题"
            style="width: 250px"
            @search="handleSearch"
          />
          <a-select
            v-model:value="categoryFilter"
            placeholder="选择分类"
            style="width: 150px"
            @change="handleCategoryChange"
          >
            <a-select-option value="">全部分类</a-select-option>
            <a-select-option v-for="category in categories" :key="category.code" :value="category.code">
              {{ category.name }}
            </a-select-option>
          </a-select>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            新增文章
          </a-button>
          <a-button @click="handleRefresh">
            <template #icon><reload-outlined /></template>
            刷新
          </a-button>
        </a-space>
      </div>

      <!-- 文章表格 -->
      <a-table
        :columns="columns"
        :data-source="articles"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <!-- 标题列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <div class="article-title">
              <a-image
                v-if="record.coverImage"
                :src="record.coverImage"
                :width="40"
                :height="40"
                :preview="false"
                style="object-fit: cover; border-radius: 4px; margin-right: 8px"
              />
              <span>{{ record.title }}</span>
            </div>
          </template>

          <!-- 分类列 -->
          <template v-if="column.key === 'category'">
            <a-tag color="blue">{{ getCategoryName(record.category) }}</a-tag>
          </template>

          <!-- 状态列 -->
          <template v-if="column.key === 'status'">
            <a-tag :color="record.isPublished ? 'green' : 'orange'">
              {{ record.isPublished ? '已发布' : '草稿' }}
            </a-tag>
            <a-tag v-if="record.isRecommended" color="purple">推荐</a-tag>
          </template>

          <!-- 操作列 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这篇文章吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a class="text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, reactive, toRefs } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { getArticleList, getArticleCategories, deleteArticle } from '@/api/article';

export default defineComponent({
  components: {
    PlusOutlined,
    ReloadOutlined
  },
  setup() {
    const router = useRouter();
    
    const state = reactive({
      articles: [],
      categories: [],
      loading: false,
      searchKeyword: '',
      categoryFilter: '',
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: (total) => `共 ${total} 条记录`
      }
    });

    // 表格列定义
    const columns = [
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        ellipsis: true
      },
      {
        title: '分类',
        dataIndex: 'category',
        key: 'category',
        width: 120
      },
      {
        title: '作者',
        dataIndex: 'author',
        key: 'author',
        width: 120
      },
      {
        title: '状态',
        key: 'status',
        width: 120
      },
      {
        title: '阅读量',
        dataIndex: 'viewCount',
        key: 'viewCount',
        width: 100,
        sorter: true
      },
      {
        title: '发布日期',
        dataIndex: 'publishDate',
        key: 'publishDate',
        width: 120,
        sorter: true
      },
      {
        title: '操作',
        key: 'action',
        width: 120
      }
    ];

    // 获取文章列表
    const fetchArticles = async () => {
      state.loading = true;
      try {
        const params = {
          page: state.pagination.current,
          pageSize: state.pagination.pageSize,
          keyword: state.searchKeyword,
          category: state.categoryFilter || undefined,
          sortField: state.sortField,
          sortOrder: state.sortOrder
        };

        const res = await getArticleList(params);
        if (res.code === 0) {
          state.articles = res.data.list;
          state.pagination.total = res.data.total;
        } else {
          message.error(res.message || '获取文章列表失败');
        }
      } catch (error) {
        console.error('获取文章列表失败:', error);
        message.error('获取文章列表失败');
      } finally {
        state.loading = false;
      }
    };

    // 获取文章分类
    const fetchCategories = async () => {
      try {
        const res = await getArticleCategories();
        if (res.code === 0) {
          state.categories = res.data;
        }
      } catch (error) {
        console.error('获取文章分类失败:', error);
      }
    };

    // 处理表格变化
    const handleTableChange = (pagination, filters, sorter) => {
      state.pagination.current = pagination.current;
      state.pagination.pageSize = pagination.pageSize;
      
      // 处理排序
      if (sorter.field) {
        state.sortField = sorter.field;
        state.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc';
      } else {
        state.sortField = undefined;
        state.sortOrder = undefined;
      }
      
      fetchArticles();
    };

    // 处理搜索
    const handleSearch = () => {
      state.pagination.current = 1;
      fetchArticles();
    };

    // 处理分类筛选
    const handleCategoryChange = () => {
      state.pagination.current = 1;
      fetchArticles();
    };

    // 处理刷新
    const handleRefresh = () => {
      fetchArticles();
    };

    // 处理新增文章
    const handleAdd = () => {
      router.push('/articles/new');
    };

    // 处理编辑文章
    const handleEdit = (record) => {
      router.push(`/articles/${record.id}`);
    };

    // 处理删除文章
    const handleDelete = async (record) => {
      try {
        const res = await deleteArticle(record.id);
        if (res.code === 0) {
          message.success('删除成功');
          fetchArticles();
        } else {
          message.error(res.message || '删除失败');
        }
      } catch (error) {
        console.error('删除文章失败:', error);
        message.error('删除失败');
      }
    };

    // 获取分类名称
    const getCategoryName = (code) => {
      const category = state.categories.find(item => item.code === code);
      return category ? category.name : code;
    };

    onMounted(() => {
      fetchCategories();
      fetchArticles();
    });

    return {
      ...toRefs(state),
      columns,
      handleTableChange,
      handleSearch,
      handleCategoryChange,
      handleRefresh,
      handleAdd,
      handleEdit,
      handleDelete,
      getCategoryName
    };
  }
});
</script>

<style scoped>
.article-list-container {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.article-title {
  display: flex;
  align-items: center;
}

.text-danger {
  color: #ff4d4f;
}
</style> 